package com.example.runningman.user;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.runningman.MainActivity;
import com.example.runningman.R;
import com.example.runningman.bean.User;
import com.example.runningman.util.SPUtil;
import com.example.runningman.view.ItemView;
import com.example.runningman.view.QMAutoTestDialogBuilder;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Calendar;

public class UserActivity extends AppCompatActivity implements View.OnClickListener{
    String phone;
    ImageButton imageButton;
    ItemView username;
    ItemView sex;
    ItemView birthday;
    ItemView cont;
    TextView username_text;
    TextView cont_text;
    TextView sex_text;
    TextView birthday_text;
    Button button;
    Button tui_button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        mHandler = new Mhandler(this);
        imageButton=findViewById(R.id.back3);
        username=findViewById(R.id.username);
        sex=findViewById(R.id.sex);
        birthday=findViewById(R.id.birthday);
        cont=findViewById(R.id.cont);
        cont_text=findViewById(R.id.cont_text);
        username_text=findViewById(R.id.username_text);
        birthday_text=findViewById(R.id.birthday_text);
        sex_text=findViewById(R.id.sex_text);
        getDate();
        imageButton.setOnClickListener(this);
        username.setOnClickListener(this);
        sex.setOnClickListener(this);
        cont.setOnClickListener(this);
        birthday.setOnClickListener(this);
        button=findViewById(R.id.queRenBtn);
        button.setOnClickListener(this);
        tui_button=findViewById(R.id.tuiChuBtn);
        tui_button.setOnClickListener(this);

        phone=SPUtil.getInstance(getApplicationContext()).getString("phone","111");
        postRequest(phone);
    }

    private static Gson gson=new Gson();
    private Mhandler mHandler;

    final OkHttpClient client = new OkHttpClient();

    @Override
    public void onClick(View v) {
        QMAutoTestDialogBuilder autoTestDialogBuilder = (QMAutoTestDialogBuilder) new QMAutoTestDialogBuilder(UserActivity.this);
        Intent intent;
        switch (v.getId()){
            case R.id.back3:
                intent=new Intent(UserActivity.this,MainActivity.class);
                startActivity(intent);
                break;
            case R.id.tuiChuBtn:
                SPUtil.getInstance(UserActivity.this).remove("phone");
                intent=new Intent(UserActivity.this,LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.birthday:
                DatePickerDialog.OnDateSetListener listener=new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker arg0, int year, int month, int day) {
                        birthday_text.setText(year+"-"+(++month)+"-"+day);   //将选择的日期显示到TextView中,因为之前获取month直接使用，所以不需要+1，这个地方需要显示，所以+1
                    }
                };
                DatePickerDialog dialog=new DatePickerDialog(UserActivity.this, 0,listener,year,month,day);//后边三个参数为显示dialog时默认的日期，月份从0开始，0-11对应1-12个月
                dialog.show();
                break;
            case R.id.username:
            case R.id.sex:
            case R.id.cont:

                autoTestDialogBuilder   .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {

                                EditText editText = autoTestDialogBuilder.getEditText();
                                if(v.getId()==R.id.username){
                                    SPUtil.getInstance(UserActivity.this).putString("username", editText.getText().toString());
                                    username_text.setText(editText.getText());
                                }else if(v.getId()==R.id.sex){
                                    sex_text.setText(editText.getText());
                                }else{
                                    cont_text.setText(editText.getText());
                                }

                                dialog.dismiss();
                            }
                        });
                autoTestDialogBuilder.show();

                QMUIKeyboardHelper.showKeyboard(autoTestDialogBuilder.getEditText(), true);

                break;
            case R.id.queRenBtn:


                String i="1";
                if(sex_text.getText()=="女"){
                    i="2";
                }else {
                    i="1";
                }

                postRequest(username_text.getText().toString(),i,birthday_text.getText().toString(),cont_text.getText().toString());
                Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                intent=new Intent(UserActivity.this,MainActivity.class);
                startActivity(intent);
                break;
        }
    }
    private Calendar cal;
    private int year,month,day;
    private void getDate() {
        cal= Calendar.getInstance();
        year=cal.get(Calendar.YEAR);    //获取年月日时分秒
        Log.i("wxy","year"+year);
        month=cal.get(Calendar.MONTH);  //获取到的月份是从0开始计数
        day=cal.get(Calendar.DAY_OF_MONTH);
    }
    private class Mhandler extends Handler {
        private WeakReference<UserActivity> mActivity;

        public Mhandler(UserActivity activity){
            mActivity = new WeakReference<>(activity);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息","+"+ReturnMessage+"+");
                User user=gson.fromJson(ReturnMessage,User.class);
                Log.i("获取的返回信息","+"+user.toString()+"+");
                cont_text.setText(user.getAccount()+"");
                username_text.setText(user.getUsername()+"");
                birthday_text.setText(user.getBirthday()+"");
                String string= "男";
                if("".equals(user.getSex()+"")||user.getSex()==null){

                }else {
                    if(user.getSex()==2){
                        string="女";
                    }
                }

                sex_text.setText(string);
                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
        }
    }
    /**
     * post请求后台
     * @param username
     */
    private void postRequest(String username)  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("phone",username)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/findUser?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void postRequest(String username,String sex,String birthday1,String contt)  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("phone",phone)
                .add("username",username)
                .add("sex",sex)
                .add("birthday",birthday1)
                .add("contt",contt)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/updateUser?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui


                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}